package com.ls.herostory.cmdhandler;

import com.ls.herostory.channel.handler.BroadCast;
import com.ls.herostory.session.MoveState;
import com.ls.herostory.session.Session;
import com.ls.herostory.session.SessionUtil;
import com.ls.herostory.msg.GameMsgProtocol;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * @author liangsu
 * @version v1.0
 * @Description
 * @Date 2020/10/12 9:28
 * @since
 */
public class UserMoveToCmdHandler implements CmdHandler<GameMsgProtocol.UserMoveToCmd> {

    @Override
    public void handleCmd(ChannelHandlerContext ctx, GameMsgProtocol.UserMoveToCmd cmd) {
        Session session = SessionUtil.getSession((NioSocketChannel) ctx.channel());

        if(session == null){
            return;
        }

        // 记录移动信息
        long time = System.currentTimeMillis();
        MoveState moveState = session.getMoveState();
        moveState.setFromPosX(cmd.getMoveFromPosX());
        moveState.setFromPosY(cmd.getMoveFromPosY());
        moveState.setToPosX(cmd.getMoveToPosX());
        moveState.setToPosY(cmd.getMoveToPosY());
        moveState.setStartTime(time);

        // 返回消息
        GameMsgProtocol.UserMoveToResult result = GameMsgProtocol.UserMoveToResult.newBuilder()
                .setMoveUserId(session.getUserId())
                .setMoveFromPosX(cmd.getMoveFromPosX())
                .setMoveFromPosY(cmd.getMoveFromPosY())
                .setMoveToPosX(cmd.getMoveToPosX())
                .setMoveToPosY(cmd.getMoveToPosY())
                .setMoveStartTime(time)
                .build();

        // 广播
        BroadCast.cast(result);
    }



}
